{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7a8170f6",
   "metadata": {},
   "source": [
    "# 输入一个数字组成的字符串，转成整数并输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5ea4ed49",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2147483647\n"
     ]
    }
   ],
   "source": [
    "#include <iostream>\n",
    "#include <cctype>\n",
    "int StrToInt(const char* str){\n",
    "    static const int MAX_INT = (int)((unsigned)~0 >> 1);\n",
    "    static const int MIN_INT = -MAX_INT - 1;\n",
    "    //std::cout <<str<<\"max : \"<<MAX_INT<<\" min : \"<<MIN_INT<< std::endl;\n",
    "    unsigned int n = 0;\n",
    "    if(str == NULL){\n",
    "        return 0;\n",
    "    }\n",
    "    while(std::isspace(*str)){\n",
    "        ++str;\n",
    "    }\n",
    "    int sign = 1;\n",
    "    if(*str == '+' || *str == '-'){\n",
    "        if(*str == '-')\n",
    "            sign = -1;\n",
    "        ++str;\n",
    "    }\n",
    "    while(std::isdigit(*str)){\n",
    "        int c = *str - '0';\n",
    "        if(sign > 0 && (n > MAX_INT / 10 || (n == MAX_INT / 10 && c > MAX_INT % 10))){\n",
    "            n = MAX_INT;\n",
    "            break;\n",
    "        }else if(sign < 0 && (n > (unsigned)MIN_INT / 10 || (n == (unsigned)MIN_INT / 10 && c > (unsigned)MIN_INT % 10))){\n",
    "            n = MIN_INT;\n",
    "            break;\n",
    "        }\n",
    "        n = n * 10 + c;\n",
    "        ++str;\n",
    "    }\n",
    "    return sign > 0 ? n : -n;\n",
    "}\n",
    "std::cout <<StrToInt(\"    124988989898989983\")<< std::endl;"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++14",
   "language": "C++14",
   "name": "xcpp14"
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "c++",
   "version": "14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
